const service = require('../service/talkService')
// 引入jwt模块
const jwt = require('../util/jwt.js')
const controller = {
  // 添加
  async addTalk(req, res) {
    const { talk, token, type } = req.body
    let username = jwt.verify(token)?.uname
    const data = await service.addTalk(talk, username, type)
    if (data.createTime) {
      res.send({ ok: 1, info: '添加完成' })
    } else {
      res.send({ ok: 0, info: '添加失败' })
    }
  },
  // 查找
  async findTalk(req, res) {
    let { page, limite, type } = req.query
    page = page ? page : '1'
    limite = limite ? limite : '7'
    type = type ? type : new RegExp('.')

    let data = await service.findTalk(page, limite, type)

    res.send({ ok: 1, info: data })
  },
  // // 查找单个
  async findTalkSingle(req, res) {
    let { id } = req.query
    id = id ? id : ''
    let data = await service.findTalkSing(id)
    res.send({ ok: 1, data })
  },
  // 删除
  async delTalk(req, res) {
    let { id } = req.params
    // 删除文件夹中文件
    let data = await service.delTalk(id)

    res.send({
      ok: data.acknowledged ? 1 : 0,
      code: 200,
      info: data.acknowledged ? '删除成功' : '删除失败',
    })
  },
  // 修改
  async updateTalk(req, res) {
    let { talk, type, token ,id} = req.body
    let username = jwt.verify(token)?.uname
    let data = await service.updateTalk(talk, type, username,id)

    if (data.acknowledged) {
      res.send({ ok: 1, info: '修改成功' })
    } else {
      res.send({ ok: 0, info: '修改失败' })
    }
  },
}

module.exports = controller
